library console;

uses common, CoreI, ConsoleI, ScriptEngineI, sdl, windows, sysutils;
var console_opened:boolean=false;
Console_Thread:PSDL_thread;
Function IsOpened:boolean; cdecl;
begin
result:=Console_Opened;
end;
Function ErrorHandler(var str:PChar; var code:cardinal):boolean; cdecl;
begin
result:=false;
if console_opened then writeln(str) else result:=true;
end;

function execute(p:pointer): integer; cdecl;
var s:string;
event:TSDL_Event;
begin
if console_opened then exit;
console_opened:=true;
Core_SetState(core_paused);
allocconsole;
setconsoletitle('Game console');
event.type_ := Event_ScriptEngine;
Event.user.code := SE_Event_ExecString;
new(PSE_ExecStringStruct(event.user.data1));
PSE_ExecStringStruct(event.user.data1)^.where := 'STDIN';
PSE_ExecStringStruct(event.user.data1)^.ErrorHandler := ErrorHandler;
getmem(PSE_ExecStringStruct(event.user.data1)^.chunk, 255);
repeat
    write('>');
readln(s);
if s = '' then break;
LStrCpy(PSE_ExecStringStruct(event.user.data1)^.chunk, PChar(s));
SDL_PushEvent(@event);
until s='';
freemem(PSE_ExecStringStruct(event.user.data1)^.chunk);
dispose(PSE_ExecStringStruct(event.user.data1));
freeconsole;
console_opened:=false;
Core_SetState(Core_LastState);
result:=1;
end;
Procedure Open; cdecl;
begin
Console_Thread:=sdl_CreateThread(@Execute, nil);
end;
var PluginInfo:PPluginInfo;
procedure Init; cdecl;
begin
Core_RequirePlugin(ScriptEngineI.ScriptEngineGUID);
end;

procedure Free; cdecl;
begin
dispose(IConsole(PluginInfo^.InterfaceStruct));
dispose(PluginInfo);
SDL_KillThread(Console_Thread);
end;

Procedure Plugin_GetInfo(var info:PPluginInfo; var length:cardinal); cdecl;
begin
new(info);
PluginInfo:=info;
info^.Name := 'Console_win';
info^.GUID := ConsoleGuid;
info^.Init := Init;
info^.free := free;
new(IConsole(info^.InterfaceStruct));
IConsole(info^.InterfaceStruct)^.Open := Open;
IConsole(info^.InterfaceStruct)^.IsOpened := IsOpened;
length:=1;
                                end;

exports Plugin_GetInfo;
begin
end.
